package org.zerg.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zerg.dao.CategoryDao;
import org.zerg.dao.ImageDao;
import org.zerg.dao.ProductDao;
import org.zerg.dto.FileDto;
import org.zerg.entity.Category;
import org.zerg.entity.Image;
import org.zerg.entity.Product;
import org.zerg.service.CategoryService;

@Service
public class CategoryServiceImpl extends BaseServiceImpl implements CategoryService{

	@Autowired
	private CategoryDao categoryDao;
	
	@Autowired
	private ImageDao imageDao;
	
	@Autowired
	private ProductDao productDao;
	
	@Value("${adImage.url}")
	private String adImageUrl;
	
	/**
	 * 注：
	 * 表级联查，如果对应的联查表无对应信息
	 * 无对应信息的字段就无法查到！
	 */
	public List<Category> categoryAll() {
		List<Category> list = categoryDao.categoryAll();
		for (Category category : list) {
			category.getImg().setUrl(adImageUrl+category.getImg().getUrl());
		}
		return list;
	}

	public void inserCategory(FileDto dto, String name) {
		String fileName = this.saveFile(dto);
		imageDao.addImage("/"+fileName);
		Image image = imageDao.getImage("/"+fileName);
		categoryDao.inserCategory(name, image.getId());
	}

	public void modifyCategoryNoFile(String name, int id) {
		categoryDao.modifyCategoryNoFile(name, id);
	}

	public void modifyCategory(FileDto dto, String name, int id) {
		String fileName = this.saveFile(dto);
		imageDao.addImage("/"+fileName);
		Image image = imageDao.getImage("/"+fileName);
		categoryDao.modifyCategory(name, image.getId(), id);
	}

	public void deleteCategory(int id) {
		categoryDao.deleteCategory(id);
	}

	public List<Product> getProductByCate(int id) {
		List<Product> list = productDao.getProductByCa(id);
		for (Product product : list) {
			product.setMainImgUrl(adImageUrl+product.getMainImgUrl());
		}
		return list;
	}

	public void modifyProductOnCate(int id, int pid) {
		productDao.modifyProductOnCategory(id, pid);
	}

	@Override
	public boolean isName(String name) {
		boolean result = true;
		Category bean = categoryDao.getCategoryByName(name);
		if(bean == null){
			result = false;
		}
		return result;
	}

}
